package so.shanku.essential.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import aym.util.sdcard.SdcardHelper;
import aym.util.versionup.IVersionSelectedCallBack;
import aym.util.versionup.VersionUpdateUtil;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import so.shanku.essential.R;
import so.shanku.essential.activity.*;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.*;
import so.shanku.essential.view.CircleImageView;
import so.shanku.essential.view.WihteRoundCornersDialog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的
 *
 * @author sk06
 */

public class UserCenterFragment extends BaseFragment {

    /**
     * 我的消息
     */
    @ViewInject(R.id.logo_msg_iv)
    private ImageView logo_msg_iv;
    /**
     * 客服
     */
    @ViewInject(R.id.custom_service_iv)
    private ImageView custom_service_iv;
    /**
     * 上传头像
     */
    @ViewInject(R.id.iv_taking_pictures)
    private CircleImageView iv_taking_pictures;

    /**
     * 用户名
     */
    @ViewInject(R.id.userNick_tv)
    private TextView userNick_tv;
    @ViewInject(R.id.userNickLayout)
    private RelativeLayout userNickLayout;

    /**
     * 个人描述
     */
    @ViewInject(R.id.user_dis_tv)
    private TextView user_dis_tv;
    @ViewInject(R.id.user_dis_layout)
    private RelativeLayout user_dis_layout;
    /**
     * 日志
     */
    @ViewInject(R.id.blog_layout)
    private LinearLayout blog_layout;
    @ViewInject(R.id.blog_num_tv)
    private TextView blog_num_tv;
    /**
     * 话题
     */
    @ViewInject(R.id.topic_layout)
    private LinearLayout topic_layout;
    @ViewInject(R.id.topic_num_tv)
    private TextView topic_num_tv;
    /**
     * 关注
     */
    @ViewInject(R.id.focus_layout)
    private LinearLayout focus_layout;
    @ViewInject(R.id.focus_num_tv)
    private TextView focus_num_tv;
    /**
     * 粉丝
     */
    @ViewInject(R.id.fans_layout)
    private LinearLayout fans_layout;
    @ViewInject(R.id.fans_num_tv)
    private TextView fans_num_tv;
    /**
     * 购物车
     */
    @ViewInject(R.id.myShopCart_layout)
    private LinearLayout myShopCart_layout;
    @ViewInject(R.id.myShopCartNum_tv)
    private TextView myShopCartNum_tv;
    /**
     * 订单
     */
    @ViewInject(R.id.myOrdersLayout)
    private LinearLayout myOrdersLayout;
    @ViewInject(R.id.myOrdersNum_tv)
    private TextView myOrdersNum_tv;
    /**
     * 我的收藏
     */
    @ViewInject(R.id.myCollectionLayout)
    private LinearLayout myCollectionLayout;
    @ViewInject(R.id.myCollectionNum_tv)
    private TextView myCollectionNum_tv;

    /**
     * 我的账户
     */
    @ViewInject(R.id.myAccountLayout)
    private LinearLayout myAccountLayout;
    @ViewInject(R.id.myAccountNum_tv)
    private TextView myAccountNum_tv;
    /**
     * 我的预约
     */
    @ViewInject(R.id.myAppointmentLayout)
    private LinearLayout myAppointmentLayout;
    @ViewInject(R.id.myAppointmentNum_tv)
    private TextView myAppointmentNum_tv;
    /**
     * 系统设置
     */
    @ViewInject(R.id.settingLayout)
    private LinearLayout settingLayout;

    private View viewCamera;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_center_layout, container, false);
        return view;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        getServerData();
    }

    private void getServerData() {

    }


    /**
     * 找Id
     */
    private void initView(View view) {
        ViewUtils.inject(this, view);
        refreshUserPhotoAndStatue();
    }

    /**
     * 我的消息
     *
     * @param view
     */
    @OnClick(R.id.logo_msg_iv)
    public void logo_msg_iv_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 联系客服
     *
     * @param view
     */
    @OnClick(R.id.custom_service_iv)
    public void custom_service_iv_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 头像
     *
     * @param view
     */
    @OnClick(R.id.iv_taking_pictures)
    public void iv_taking_pictures_click(View view) {
        showModPhotosView();
    }

    /**
     * 昵称
     *
     * @param view
     */
    @OnClick(R.id.userNickLayout)
    public void userNickLayout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 个人资料
     *
     * @param view
     */
    @OnClick(R.id.user_dis_layout)
    public void user_dis_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 日志
     *
     * @param view
     */
    @OnClick(R.id.blog_layout)
    public void blog_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 话题
     *
     * @param view
     */
    @OnClick(R.id.topic_layout)
    public void topic_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 关注
     *
     * @param view
     */
    @OnClick(R.id.focus_layout)
    public void focus_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 粉丝
     *
     * @param view
     */
    @OnClick(R.id.fans_layout)
    public void fans_layout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 购物车
     *
     * @param view
     */
    @OnClick(R.id.myShopCart_layout)
    public void myShopCart_layout_click(View view) {
        Intent personData = new Intent(activity, ShopCartActivity.class);
        startActivity(personData);
    }

    /**
     * 我的订单
     *
     * @param view
     */
    @OnClick(R.id.myOrdersLayout)
    public void myOrdersLayout_click(View view) {
        //全部订单
        Intent personOrder = new Intent(activity, UserOrderActivity.class);
        startActivity(personOrder);
    }

    /**
     * 我的搜藏
     *
     * @param view
     */
    @OnClick(R.id.myCollectionLayout)
    public void myCollectionLayout_click(View view) {
        Intent personCollection = new Intent(activity, UserCollectionActivity.class);
        startActivity(personCollection);
    }

    /**
     * 我的预约
     *
     * @param view
     */
    @OnClick(R.id.myAppointmentLayout)
    public void myAppointmentLayout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 我的账户
     *
     * @param view
     */
    @OnClick(R.id.myAccountLayout)
    public void myAccountLayout_click(View view) {
        Intent personData = new Intent(activity, UserDataActivity.class);
        startActivityForResult(personData, personcenter);
    }

    /**
     * 系统设置
     *
     * @param view
     */
    @OnClick(R.id.settingLayout)
    public void settingLayout_click(View view) {
        Intent personData = new Intent(activity, SetActivity.class);
        startActivity(personData);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        refreshUserPhotoAndStatue();
    }

    /**
     * 刷新头像和信息
     */
    private void refreshUserPhotoAndStatue() {
        user_dis_tv.setText(Utils.getUserDiscri(activity));
        userNick_tv.setText(Utils.getUserNickNameOrAccount(activity));
        ImageLoader.getInstance().displayImage(Utils.getUserPic(activity), iv_taking_pictures, MyApplication.getInstance().getUserHeadOption(), new ImageLoaderBitmapCallBack());
    }


    /**
     * “我的”点击事件
     */
    View.OnClickListener myclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
            switch (id) {
                case R.id.select_v:
                    popupWindow.dismiss();
                    break;

                case R.id.bt_my_log_out:
                    //退出登录
                    showExitDialog();
                    break;

                default:
                    break;
            }
        }
    };
    /**
     * 更多的点击事件
     */
    View.OnClickListener moreAndMore = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
//            switch (id) {
//                case R.id.tr_my_about_us:
//                    //关于我们
//                    Intent aboutIntent = new Intent(activity, UrlWebviewActivity.class);
//                    aboutIntent.putExtra(ExtraKeys.Key_Msg1, 7);
//                    activity.jumpTo(aboutIntent, false);
//                    break;
//                case R.id.tr_my_help_center:
//                    //帮助中心
//                    Intent intent = new Intent(activity, UrlWebviewActivity.class);
//                    intent.putExtra(ExtraKeys.Key_Msg1, 1);
//                    activity.jumpTo(intent, false);
//                    break;
//                case R.id.tr_my_feedback:
//                    //意见反馈
//                    activity.jumpTo(UserFeedBackActivity.class);
//                    break;
//                case R.id.tr_my_version_checking:
//                    //版本检测
//                    upversion();
//                    break;
//
//                case R.id.tr_my_contact_us:
//                    //联系我们
//                    activity.jumpTo(ContactUsActivity.class);
//                    break;
//            }
        }
    };

    // 版本升级的工具
    private VersionUpdateUtil util;
    // 内存卡管理的帮助类
    private SdcardHelper sdHelper;

    /**
     * 检测版本
     */
    private void upversion() {
        util = VersionUpdateUtil.init(activity);
        if (!sdHelper.ExistSDCard()) {
            toast.showToast(R.string.nosdcard);
        } else {
            util.doSelectVersion(GetDataConfing.ip,
                    GetDataConfing.Action_selectAppVersionInfo, null, false,
                    versionSelectedCallBack);
        }

    }

    String apkDownLoadPath;

    /**
     * 提示用户有新版本
     */
    private void showNewVersion(JsonMap<String, Object> info,
                                String versionName, int versionCode) {
        apkDownLoadPath = info.getStringNoNull("VersionPath");
        builder = new WihteRoundCornersDialog(activity,
                R.style.ExitDialogStyle, 2, callBackdialog1);
        builder.setTitletext(R.string.app_version_select);
        builder.setMessagetext(info.getStringNoNull("Description"));
        builder.setButtonText(R.string.app_version_iknow, R.string.app_version_update);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog1 = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    String appName = getString(R.string.app_name);
                    util.doUpdateVersion(apkDownLoadPath,
                            Confing.productPath + appName + ".apk",
                            appName, R.drawable.app_icon, true);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

    IVersionSelectedCallBack versionSelectedCallBack = new IVersionSelectedCallBack() {
        @Override
        public void netError(String arg0) {
            toast.showToast(R.string.neterror);
        }

        @Override
        public boolean isUpdate(String serviceInfo, String versionName,
                                int versionCode) {
            try {
                serviceInfo = serviceInfo.substring(serviceInfo.indexOf("{"),
                        serviceInfo.lastIndexOf("}") + 1);
            } catch (Exception e) {
                e.printStackTrace();

                return false;
            }
            if (ShowGetDataError.isCodeIsNot1(activity, serviceInfo)) {
                List<JsonMap<String, Object>> infoData = JsonParseHelper
                        .getJsonMap_List_JsonMap(serviceInfo, JsonKeys.Key_Info);
                if (infoData.size() == 0) {

                } else {
                    JsonMap<String, Object> info = infoData.get(0);
                    if (info.getStringNoNull("VersionNo").equals(versionName)
                            || "".equals(info.getStringNoNull("VersionNo"))
                            || "".equals(info.getStringNoNull("VersionPath"))) {
                        toast.showToast(R.string.app_version_newest);
                    } else {
                        showNewVersion(info, versionName, versionCode);
                    }
                }

            } else {

            }
            return false;
        }
    };


    /**
     * 退出dialog
     */
    WihteRoundCornersDialog builder;

    private void showExitDialog() {
        builder = new WihteRoundCornersDialog(activity,
                R.style.ExitDialogStyle, 2, callBackdialog);
        builder.setTitletext(R.string.app_version_prompt);
        builder.setMessagetext(R.string.change_user);
        builder.setButtonText(R.string.cancel, R.string.ensure);
        builder.show();
    }

    private WihteRoundCornersDialog.DialogCallBack callBackdialog = new WihteRoundCornersDialog.DialogCallBack() {

        @Override
        public void bttonclick(int index) {
            builder.dismiss();
            switch (index) {
                case 1:

                    break;
                case 2:
                    clearUserBindTag();
                    Utils.clearUserInfoData(activity);
                    MyApplication.getInstance().setAttentionBrands(null);
                    MyApplication.getInstance().setPushMsgCount(0);
                    MyApplication.getInstance().setShopcart_num(0);
                    Intent intentLogin = new Intent(activity, NoLoginActivity.class);
                    intentLogin.putExtra(ExtraKeys.Key_Msg1, 0);
                    activity.jumpTo(intentLogin, true);

                    break;
                default:
                    break;
            }
        }

        @Override
        public void bttonclick(int index, int what) {

        }

    };

    private void clearUserBindTag() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("userId", Utils.getUserId(activity));
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_LoginOut);
        queue.setParamsNoJson(params);
        queue.setCallBack(new GetServicesDataUtil.IGetServicesDataCallBack() {
            @Override
            public void onLoaded(GetServicesDataQueue entity) {
                LogUtil.d(TAG, entity.getInfo());
            }
        });
        getDataUtil.getData(queue);
    }


    public PopupWindow popupWindow;
    private TextView select_photo_camera_bt;
    private TextView select_photo_local_bt;
    private final int select_local_requestcode = 1;
    private final int select_camera_requestcode = 3;
    private final int crop_requestcode = 4;
    private final int attentionbrand = 7;
    private final int personcenter = 8;//个人中心
    /**
     * 存放照片的文件
     */
    private File image;

    private void showModPhotosView() {
        if (popupWindow == null) {
            View view = activity.getLayoutInflater().inflate(R.layout.select_photo, null);
            popupWindow = new PopupWindow(view,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(view);
            popupWindow.setAnimationStyle(R.style.popupAnimation);
            select_photo_camera_bt = (TextView) view
                    .findViewById(R.id.select_photo_camera_bt);
            select_photo_local_bt = (TextView) view
                    .findViewById(R.id.select_photo_local_bt);
            View select_v = (View) view.findViewById(R.id.select_v);
            select_photo_local_bt.setOnClickListener(cameraClick);
            select_photo_camera_bt.setOnClickListener(cameraClick);
            select_v.setOnClickListener(myclick);
            popupWindow.showAtLocation(iv_taking_pictures, Gravity.NO_GRAVITY, 0, 0);

        } else if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(iv_taking_pictures, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    private OnClickListener cameraClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.select_photo_local_bt) {
                Intent intent = CropImage.getImageClipIntent_KITKAT();
                startActivityForResult(intent, select_local_requestcode);

            } else if (id == R.id.select_photo_camera_bt) {
                startCamera(select_camera_requestcode);
            }
            popupWindow.dismiss();
        }
    };

    private void startCamera(int position) {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        File file = new File(Confing.productPath
                + "/MyPhoto");
        if (!file.exists()) {
            file.mkdirs();
        }
        image = new File(file, "myphoto.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));

        startActivityForResult(intent, position);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case personcenter:
                    refreshUserPhotoAndStatue();
                    break;

                case attentionbrand:
                    ((MainActivity) activity).setSelectItem(3);
                    break;

                case select_camera_requestcode:
                    doCropPhoto(Uri.fromFile(image));
                    break;

//                case select_local_requestcode_kitkat:

                case select_local_requestcode:
                /* 将Bitmap设定到ImageView */
                    Uri selectedImage = data.getData();
                    String imagePath = PicHelper.getPath(activity, selectedImage); // 获取图片的绝对路径
                    Uri newUri = Uri.parse("file:///" + imagePath); // 将绝对路径转换为URL
                    doCropPhoto(newUri);
                    break;
                case crop_requestcode:
                    try {
                        /* 将Bitmap设定到ImageView */
                        Bitmap bitmap = data.getParcelableExtra("data");
//						user_photo_iv.setImageBitmap(bitmap);
                        // // 将图片转为string
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        String uploadBuffer = new String(Base64.encode(
                                baos.toByteArray(), Base64.DEFAULT)); // 进行Base64编码

                        String fileType = "png";
                        upLoadUserPic(uploadBuffer, fileType);
                    } catch (Exception e) {
                        toast.showToast(R.string.user_updata_pic_error);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 上传用户头像 (调用接口)
     */
    private void upLoadUserPic(String fileText, String fileType) {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, "userHeaderPic");
        params.put("userName", Utils.getUserAccount(activity));
        params.put("headerPicContent", fileText);
        params.put("headerPicType", fileType);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_UpdateUserHeaderPic);
        queue.setParamsNoJson(params);
        queue.setCallBack(new GetServicesDataUtil.IGetServicesDataCallBack() {
            @Override
            public void onLoaded(GetServicesDataQueue entity) {
                if (entity.isOk()) {
                    if (ShowGetDataError.isOkAndCodeIsNot1(activity,
                            entity.getInfo())) {
                        toast.showToast(R.string.uploading_success);
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        String headerPicPath = data.get(0).getStringNoNull("headerPicPath");
                        ImageLoader.getInstance().displayImage(headerPicPath, iv_taking_pictures, MyApplication.getInstance().getDefaultOption(), new ImageLoaderBitmapCallBack());
                        Utils.saveUserPic(activity, headerPicPath);
                    }
                } else {
                    ShowGetDataError.showNetError(activity);
                }
                loadingToast.dismiss();
            }
        });
        getDataUtil.getData(queue);
    }

    /**
     * 加载剪裁
     */
    protected void doCropPhoto(Uri imageUri) {
        try {
            // 启动gallery去剪辑这个照片
            Intent intent = CropImage.getSquareCropImageIntent(imageUri);
            startActivityForResult(intent, crop_requestcode);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 点击banck见
     *
     * @return
     */
    @Override
    public boolean backKeyClick() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return true;
        } else {
            return false;
        }
    }

}
